package javase.ch05.homeWork;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient {
    public static void main(String[] args) {
        System.out.println("---------- 我们的世界 ----------");
        Socket socket = null;
        BufferedWriter bw = null;
        BufferedReader br = null;
        Scanner sc = new Scanner(System.in);

        try {
            socket = new Socket("127.0.0.1", 10086);
            System.out.println("成功进入独属我们的世界~~~");
             bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
             br = new BufferedReader(new InputStreamReader(socket.getInputStream()));


            //开启线程接受信息
            new Thread(new ReadThread(socket)).start();
            //开始聊天
            talk2All(bw);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                bw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //往服务器写入数据
    private static void talk2All(BufferedWriter bw) throws IOException {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入要发送的内容：");
            String msg = sc.nextLine();
            bwMessage(msg, bw);
        }
    }

    public static  void bwMessage(String Message, BufferedWriter bw){
        try {
            bw.write(Message);
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

class ReadThread implements Runnable{
    Socket socket;
    public ReadThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
            try {
                //读取服务器发来的信息
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                String message;
                while((message=br.readLine())!=null){
                    if(message.equals("exit")){
                        break;
                    }

                    System.out.println(message);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

    }
}